<template>
    <div class="user-container">
        <!-- 搜索区域 -->
        <div class="search-bar">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item>
                    <el-input v-model="searchForm.userName" placeholder="请输入用户名" style="width: 150px;" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="searchForm.email" placeholder="请输入邮箱" style="width: 180px;" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="searchForm.phone" placeholder="请输入手机号" style="width: 170px;" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="success" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 表格区域 -->
        <el-table 
            :data="tableData" 
            border 
            style="width: 100%" 
            v-loading="loading"
            :height="400"
            :row-style="{height:'60px'}"
            :cell-style="{padding:'0px'}"
            :header-row-style="{height:'50px'}"
            :header-cell-style="{padding:'0px'}">
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="userName" label="用户名" width="120" align="center"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="180" align="center"></el-table-column>
            <el-table-column prop="phone" label="手机号" width="120" align="center"></el-table-column>
            <el-table-column prop="roleName" label="角色" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getRoleTagType(scope.row.roleId)">
                        {{ scope.row.roleName }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
            <el-table-column label="操作" width="180" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        circle
                        class="operation-button"
                        @click="handleEdit(scope.row)"
                        title="编辑">
                    </el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        icon="el-icon-delete"
                        circle
                        class="operation-button"
                        @click="handleDelete(scope.row)"
                        title="删除">
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div class="pagination-container">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-sizes="[5, 10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" >
                    <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select 
                        v-model="form.roleId" 
                        placeholder="请选择角色" 
                        style="width: 100%"
                        :disabled="!!form.id"
                        @focus="getRoles">
                        <el-option
                            v-for="item in roleOptions"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch
                        v-model="form.status"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="启用"
                        inactive-text="禁用">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment'
import { getRoleList } from '@/http/modules/admin.js'
export default {
    name: 'User',
    data() {
        return {
            loading: false,
            dialogVisible: false,
            dialogTitle: '',
            roleOptions: [],
            // 搜索表单
            searchForm: {
                userName: '',
                email: '',
                phone: ''
            },
            // 表格数据
            tableData: [],
            // 分页参数
            page: 1,
            pageSize: 5,
            total: 0,
            // 表单数据
            form: {
                id: null,
                userName: null,
                password: null,
                email: null,
                phone: null,
                roleId:null,
                roleName:null,
                status: 1
            },
            // 表单验证规则
            rules: {
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                roleId: [
                    { required: true, message: '请选择角色', trigger: 'change' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.fetchData()
    },
    methods: {
        // 获取表格数据
        async fetchData() {
            try {
                this.loading = true
                const params = {
                    page: this.page,
                    pageSize: this.pageSize
                }
                const res = await this.$http.user.getAll(params)
                if (res.data.code === 200) {
                    this.tableData = res.data.data
                    this.total = res.data.total
                }
            } catch (error) {
                console.error('获取用户列表失败:', error)
                this.$message.error('获取用户列表失败')
            } finally {
                this.loading = false
            }
        },
        // 搜索
        async handleSearch() {
            try {
                this.loading = true
                const params = {
                    page: this.page,
                    pageSize: this.pageSize,
                    ...this.searchForm
                }
                const res = await this.$http.user.getByCondition(params)
                if (res.data.code === 200) {
                    this.tableData = res.data.data
                    this.total = res.data.total
                }
            } catch (error) {
                console.error('搜索失败:', error)
                this.$message.error('搜索失败')
            } finally {
                this.loading = false
            }
        },
        // 重置搜索
        resetSearch() {
            this.searchForm = {
                userName: '',
                email: '',
                phone: ''
            }
            this.page = 1
            this.fetchData()
        },
        // 新增用户
        handleAdd() {
            this.dialogTitle = '新增用户'
            this.dialogVisible = true
            this.form = {
                id: null,
                userName: null,
                password: null,
                email: null,
                phone: null,
                roleId:null,
                status: 1
            }
        },
        // 编辑用户
        handleEdit(row) {
            this.dialogTitle = '编辑用户'
            this.dialogVisible = true
            this.form = { ...row }
        },
        // 删除用户
        handleDelete(row) {
            this.$confirm('确认删除该用户?', '提示', {
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await this.$http.user.deleteUser(row.id)
                    if (res.data.code === 200) {
                        this.$message.success('删除成功')
                        this.fetchData()
                    }
                } catch (error) {
                    this.$message.error('删除失败')
                }
            }).catch(() => {})
        },
        // 提交表单
        submitForm() {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await this.$http.user.save(this.form)
                        if (res.data.code === 200) {
                            this.$message.success(this.form.id ? '更新成功' : '新增成功')
                            this.dialogVisible = false
                            this.fetchData()
                        } else {
                            this.$message.error(res.data.msg || '操作失败')
                        }
                    } catch (error) {
                        this.$message.error('操作失败')
                    }
                }
            })
        },
        // 分页大小改变
        handleSizeChange(val) {
            this.pageSize = val
            this.fetchData()
        },
        // 当前页改变
        handleCurrentChange(val) {
            this.page = val
            this.fetchData()
        },
        // 格式化时间
        formatDateTime(time) {
            return time ? moment(time).format('YY-MM-DD HH:mm:ss') : '--'
        },
        // 获取角色列表
        async getRoles() {
            try {
                const res =  await getRoleList()
                //const res = await http.admin.getRoleList()
                //console.log(res)
                if (res.data.code === 200) {
                    this.roleOptions = res.data.data
                }
            } catch (error) {
                console.log(error)
                this.$message.error('获取角色列表失败')
            }
        },
        // 获取角色标签类型
        getRoleTagType(roleId) {
            const typeMap = {
                1: 'success',  // 生产方
                2: 'warning',  // 加工方
                3: 'danger'    // 管理员
            }
            return typeMap[roleId] || 'info'
        }
    }
}
</script>

<style scoped>
.user-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 100px);
}

.search-bar {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    align-items: center;
}

/* 重置输入框样式 */
.search-form .el-input__inner {
    background-color: #fff;
    border: 1px solid #dcdfe6;
    color: #606266;
    text-align: left;
}

.search-form .el-input__inner:hover {
    border-color: #c0c4cc;
}

.search-form .el-input__inner:focus {
    border-color: #409EFF;
}

.el-button + .el-button {
    margin-left: 12px;
}

.el-table {
    margin-top: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.pagination-container {
    text-align: right;
    margin-top: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 操作按钮样式 */
.operation-button.el-button.is-circle {
    width: 36px;
    height: 36px;
    padding: 9px;
    transition: all 0.3s ease;
    margin: 0 8px;
}

.operation-button.el-button.is-circle [class^="el-icon-"] {
    font-size: 16px;
    line-height: 1;
    vertical-align: -1px;
}

.operation-button.el-button.is-circle:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 编辑按钮特定样式 */
.operation-button.el-button--primary.is-circle {
    background: linear-gradient(135deg, #409EFF, #3a8ee6);
}

/* 删除按钮特定样式 */
.operation-button.el-button--danger.is-circle {
    background: linear-gradient(135deg, #f56c6c, #e74c3c);
}

/* 表单输入框左对齐 */
.el-form-item .el-input__inner,
.el-form-item .el-input-number__decrease,
.el-form-item .el-input-number__increase {
    text-align: left;
}

/* 设置表格行高 */
.el-table /deep/ .el-table__row {
    height: 67px !important;
}

/* 设置表头行高 */
.el-table /deep/ .el-table__header-row {
    height: 55px !important;
}

/* 设置单元格内边距和行高 */
.el-table /deep/ .cell {
    padding: 0 !important;
    line-height: 69px;
}

/* 设置表头单元格行高 */
.el-table /deep/ .el-table__header .cell {
    line-height: 50px;
}

/* 对话框表单样式 */
.dialog-form {
    padding: 20px 20px 0 20px;
}

.dialog-form .el-form-item {
    margin-bottom: 20px;
}

.dialog-form .el-input__inner,
.dialog-form .el-select .el-input__inner,
.dialog-form .el-date-editor.el-input__inner,
.dialog-form .el-input-number .el-input__inner {
    text-align: left;
}
</style> 